package org.jadelyre.core.task;

import org.jadelyre.core.Channel;
import org.jadelyre.core.exception.JadelyreException;
import org.jadelyre.core.worker.Worker;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;


public class CloseTask extends Task<Channel> {

//    private JadeLyre jadeLyre;

    public CloseTask(Worker<Channel> worker) {
        super(worker);
//        this.jadeLyre = jadeLyre;
//        executor = jadeLyre.getWorkerFactory().getCloseWorker();
    }

    @Override
    protected <T> void work(T t) throws JadelyreException {
        Channel channel = (Channel) t;
//        channel.getSendTask().setTerminated(true);
//        channel.getHandleTask().setTerminated(true);
//        channel.getDecodeTask().setTerminated(true);
        //这个顺序才行嘛
        channel.getDecodeWorker().setTerminated(true);
        channel.getHandleWorker().setTerminated(true);
        channel.getSendWorker().setTerminated(true);
        AsynchronousSocketChannel asynchronousSocketChannel = channel.getAsynchronousSocketChannel();
        try {
            if (asynchronousSocketChannel.isOpen()) {
                asynchronousSocketChannel.shutdownInput().shutdownOutput().close();
            }
        } catch (IOException e) {
            throw new JadelyreException(e);
        }
    }

    @Override
    protected boolean isStarted() {
        //通常是返回启动的，以正常结束关闭任务
        return true;
    }
}
